<template>
  <div class="device-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <el-button 
            type="primary" 
            @click="handleAddDevice"
          >
            添加设备
          </el-button>
        </div>
      </template>
      
      <!-- 设备列表 -->
      <div v-if="!loading" class="device-list">
        <template v-if="devices.length > 0">
          <el-table :data="devices" style="width: 100%">
            <el-table-column prop="name" label="设备名称" />
            <el-table-column prop="deviceNumber" label="设备编号" />
            <el-table-column prop="type" label="设备类型" />
            <el-table-column prop="description" label="设备描述" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
                  {{ row.status === 'online' ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleViewDevice(row.id)"
                >
                  查看
                </el-button>
                <el-button 
                  type="info" 
                  size="small" 
                  @click="handleShareDevice(row.id)"
                >
                  分享
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteDevice(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div v-else class="empty-state">
          <el-empty description="暂无设备" />
        </div>
      </div>
      
      <!-- 加载中 -->
      <div v-else class="loading-state">
        <div class="loading-content">
          <div class="el-icon-loading"></div>
          <span>加载设备中...</span>
        </div>
      </div>
    </el-card>
    
    <!-- 添加设备对话框 -->
    <el-dialog
      title="添加设备"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="deviceForm" :model="newDevice" :rules="rules" label-width="100px">
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input v-model="newDevice.deviceNumber" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="newDevice.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="newDevice.type" placeholder="请选择设备类型">
            <el-option label="智能牵引板" value="智能牵引板" />
            <el-option label="其他设备" value="其他设备" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备描述" prop="description">
          <el-input 
            v-model="newDevice.description" 
            type="textarea" 
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import { deviceApi } from '../services/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DeviceList',
  setup() {
    const userStore = inject('userStore')
    const router = useRouter()
    const devices = ref([])
    const loading = ref(true)
    const dialogVisible = ref(false)
    
    const newDevice = reactive({
      deviceNumber: '',
      name: '',
      type: '智能牵引板',
      description: ''
    })
    
    const rules = {
      deviceNumber: [
        { required: true, message: '请输入设备编号', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入设备名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择设备类型', trigger: 'change' }
      ]
    }
    
    // 加载设备列表
    const loadDevices = async () => {
      if (!userStore.currentUser.value?.id) return
      
      try {
        loading.value = true
        const response = await deviceApi.getUserDevices(userStore.currentUser.value.id)
        devices.value = response.data || []
      } catch (error) {
        console.error('加载设备失败:', error)
        ElMessage.error('加载设备失败')
      } finally {
        loading.value = false
      }
    }
    
    // 添加设备
    const handleAddDevice = () => {
      // 重置表单
      Object.keys(newDevice).forEach(key => {
        if (key === 'type') {
          newDevice[key] = '智能牵引板'
        } else {
          newDevice[key] = ''
        }
      })
      dialogVisible.value = true
    }
    
    // 确认添加设备
    const confirmAddDevice = async () => {
      try {
        // 表单验证
        if (!newDevice.deviceNumber || !newDevice.name) {
          ElMessage.warning('请填写必填项')
          return
        }
        
        const response = await deviceApi.createDevice(newDevice)
        if (response.data) {
          ElMessage.success('设备添加成功')
          dialogVisible.value = false
          loadDevices() // 重新加载列表
        }
      } catch (error) {
        console.error('添加设备失败:', error)
        ElMessage.error('添加设备失败')
      }
    }
    
    // 查看设备详情
    const handleViewDevice = (deviceId) => {
      router.push(`/device/${deviceId}`)
    }
    
    // 分享设备
    const handleShareDevice = (deviceId) => {
      router.push(`/share?id=${deviceId}`)
    }
    
    // 删除设备
    const handleDeleteDevice = async (deviceId) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除该设备吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await deviceApi.deleteDevice(deviceId)
        ElMessage.success('设备删除成功')
        loadDevices() // 重新加载列表
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除设备失败:', error)
          ElMessage.error('删除设备失败')
        }
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadDevices()
    })
    
    return {
      devices,
      loading,
      dialogVisible,
      newDevice,
      rules,
      handleAddDevice,
      confirmAddDevice,
      handleViewDevice,
      handleShareDevice,
      handleDeleteDevice
    }
  }
}
</script>

<style scoped>
.device-list-container {
  padding: 10px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.loading-content .el-icon-loading {
  width: 32px;
  height: 32px;
  animation: rotating 1s linear infinite;
  color: #409eff;
  font-size: 32px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.device-list {
  margin-top: 15px;
  overflow-x: auto;
  width: 100%;
}

.empty-state,
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

/* 表格容器，允许水平滚动 */
:deep(.el-table) {
  min-width: 100%;
  display: block;
  overflow-x: auto;
}

/* 调整操作按钮在小屏幕上的显示 */
:deep(.el-table__column--fixed-right) {
  z-index: 10;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .device-list-container {
    padding: 8px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-header .el-button {
    width: 100%;
  }
  
  /* 调整表格列宽 */
  :deep(.el-table-column) {
    min-width: 80px;
  }
  
  /* 调整对话框宽度 */
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto !important;
  }
  
  /* 调整操作按钮大小和间距 */
  :deep(.el-table__fixed-right .el-button) {
    margin-bottom: 5px;
    padding: 5px 10px;
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  /* 进一步调整表格样式，确保在极小屏幕上也能正常显示 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table__header-wrapper th) {
    padding: 10px 5px;
  }
  
  :deep(.el-table__body-wrapper td) {
    padding: 10px 5px;
  }
  
  /* 操作列中的按钮设置为垂直排列 */
  :deep(.el-table__fixed-right .el-button) {
    display: block;
    width: 100%;
    margin-bottom: 5px;
    padding: 5px 8px;
  }
  
  /* 减少按钮文字，适配小屏幕 */
  .el-button {
    padding: 8px 15px;
  }
}
</style>